<template>
  <div class="inside-comment">
    <div v-if="!showIframe" class="apply-container">
      <div class="layout">
        <div class="job-detail">
          <div class="job-header">
              <div class="top">
                  <p class="tit">{{ jobDetail.name }}</p>
                  <span class="period">报名时间：{{ dayjs(jobDetail.startTime).format('YYYY-MM-DD') }} - {{ dayjs(jobDetail.deadline).format('YYYY-MM-DD') }}</span>
              </div>
              <div class="requirements">
                  <div class="requirement-item">
                      <el-icon><School /></el-icon>
                      {{ getDegreeLabel(jobDetail.degree) || '学历不限' }}
                  </div>
                  <el-divider direction="vertical" />
                  <div class="requirement-item">
                      <el-icon><Timer /></el-icon>
                      {{ getExperienceLabel(jobDetail.workExperience) || '经验不限' }}
                  </div>
                  <el-divider direction="vertical" />
                  <div class="requirement-item">
                      <el-icon><Location /></el-icon>
                      {{ jobDetail.address || '地点未设置' }}
                  </div>
                  <el-divider direction="vertical" />
                  <div class="requirement-item">
                      <el-icon><User /></el-icon>
                      {{ jobDetail.age || '年龄不限' }}
                  </div>
                  <el-divider direction="vertical" />
                  <div class="requirement-item">
                      招聘{{ jobDetail.num }}人
                  </div>
              </div>
              <div class="job-tags">
                <el-tag type="info" v-for="tag in jobDetail.customizationList" :key="tag">{{ tag }}</el-tag>
              </div>
              <div class="job-actions">
                  <el-button v-if="jobDetail && jobDetail.state === 4" type="primary" @click="handleApply">申请职位</el-button>
                  <el-button :type="jobDetail.isCollect?'primary':''" plain :icon="jobDetail.isCollect ? StarFilled : Star" @click="toggleFavorite(jobDetail)">{{ jobDetail.isCollect ? '已收藏' : '收藏' }}</el-button>
                  <el-popover placement="right" :width="200" trigger="click" @show="generateQRCode(jobDetail.id)" @click.stop>
                    <template #reference>
                      <el-button plain :icon="Share" @click.stop>分享</el-button>
                    </template>
                    <div class="share-content">
                      <img v-if="qrcodeUrls[jobDetail.id]" :src="qrcodeUrls[jobDetail.id]" class="qrcode-img" alt="分享二维码" />
                      <div class="share-link">
                        <el-input v-model="shareLinks[jobDetail.id]" size="small" readonly>
                          <template #append>
                            <el-button @click="copyLink(jobDetail.id)">复制</el-button>
                          </template>
                        </el-input>
                      </div>
                      <div class="share-tip">扫描二维码分享</div>
                    </div>
                  </el-popover>
              </div>
          </div>
          <div class="job-main">
              <div class="job-section">
                  <h2>专业要求</h2>
                  <div class="content">{{ jobDetail.major || '不限' }}</div>
                </div>
        
                <div class="job-section">
                  <h2>职位描述</h2>
                  <div class="content" v-html="formatContent(jobDetail.description)"></div>
                </div>
          </div>
          <!-- 相关职位 -->
          <div class="related-jobs">
            <h2>相关职位</h2>
            <ul class="job-list" v-loading="relatedLoading">
              <li v-for="job in relatedList" :key="job.id">
                <div class="top">
                  <p class="tit">{{ job.name }}</p>
                  <span class="period">报名时间：{{ dayjs(job.startTime).format('YYYY-MM-DD') }} - {{ dayjs(job.deadline).format('YYYY-MM-DD') }}</span>
                </div>
                <div class="requirements">
                    <div class="requirement-item">
                        <el-icon><School /></el-icon>
                        {{ getDegreeLabel(job.degree) || '学历不限' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                        <el-icon><Timer /></el-icon>
                        {{ getExperienceLabel(job.workExperience) || '经验不限' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                        <el-icon><Collection /></el-icon>
                        {{ job.major || '专业不限' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                        <el-icon><Location /></el-icon>
                        {{ job.address || '地点未设置' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                        <el-icon><User /></el-icon>
                        {{ job.age || '年龄不限' }}
                    </div>
                </div>
                <div class="bottom">
                  <div class="job-tags">
                    <el-tag type="info" v-for="tag in job.customizationList" :key="tag">{{ tag }}</el-tag>
                  </div>
                  <div class="btns">
                    <el-button type="primary" @click="handleJobClick(job.id)">查看详情</el-button>
                    <el-button :type="job.isCollect?'primary':''" plain :icon="job.isCollect ? StarFilled : Star" @click="toggleFavorite(job)">{{ job.isCollect ? '已收藏' : '收藏' }}</el-button>
                    <el-popover placement="right" :width="200" trigger="click" @show="generateQRCode(job.id)" @click.stop>
                        <template #reference>
                          <el-button plain :icon="Share" @click.stop>分享</el-button>
                        </template>
                        <div class="share-content">
                          <img v-if="qrcodeUrls[job.id]" :src="qrcodeUrls[job.id]" class="qrcode-img" alt="分享二维码" />
                          <div class="share-link">
                            <el-input v-model="shareLinks[job.id]" size="small" readonly>
                              <template #append>
                                <el-button @click="copyLink(job.id)">复制</el-button>
                              </template>
                            </el-input>
                          </div>
                          <div class="share-tip">扫描二维码分享</div>
                        </div>
                      </el-popover>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <!-- 侧边栏 -->
        <div class="job-sidebar">
            <div class="sidebar-card">
                <h3>医院信息</h3>
                <div class="sidebar-info">
                  <el-icon><OfficeBuilding /></el-icon>
                  <p>某某医院</p>
                </div>
                <div class="sidebar-info">
                  <el-icon><Location /></el-icon>
                  <p>XX市XX区XX路XX号</p>
                </div>
                <div class="sidebar-info">
                  <el-icon><Phone /></el-icon>
                  <p>010-12345678</p>
                </div>
                <div class="sidebar-info">
                  <el-icon><Paperclip /></el-icon>
                  <p><a href="#">医院官网</a></p>
                </div>
            </div>
            <div class="sidebar-card">
                <h3>联系人</h3>
                <div class="sidebar-info">
                  <el-icon><User /></el-icon>
                  <p>张主任</p>
                </div>
                <div class="sidebar-info">
                  <el-icon><Phone /></el-icon>
                  <p>010-12345678</p>
                </div>
                <div class="sidebar-info">
                  <el-icon><Postcard /></el-icon>
                  <p><a href="mailto:hr@xxxhospital.com">hr@xxxhospital.com</a></p>
                </div>
            </div>
        </div>
      </div>
    </div>
    <!-- <div v-else class="iframe-container" v-loading="formLoading" element-loading-text="表单加载中">
      <iframe ref="applyIframe" class="apply-iframe" :src="formUrl" @load="handleIframeLoad"></iframe>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Share,School, Timer, User, Location,Star, StarFilled,OfficeBuilding, Phone, Paperclip, Postcard, Collection } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { selectPostById, selectFormLink, insertPostCollect, deletePostCollect,selectRecommend } from '@/api/position'
import { encrypt, getToken } from '@ruifox-cms/utils'
import dayjs from 'dayjs'
import QRCode from 'qrcode'
import { useStore } from "vuex";
import { myDebounce } from '@/utils/tools'

const store = useStore();
const route = useRoute()
const router = useRouter()
const hasToken = ref(!!getToken())
const showIframe = ref(false)

// 模拟职位详情数据
const jobDetail = ref({})
const handleGetJobDetail = async () => {
  const res = await selectPostById({ id: route.query.jobId })
  if (res.code === 20000) {
    jobDetail.value = res.data
    getRecommend(res.data);
  }
}

// 筛选配置
const filterGroups = ref([
  {
    id: 'degree',
    title: '学历要求',
    multiple: false, // 单选模式
    options: [
      { value: '', label: '不限' },
      { value: '1', label: '初中及以下' },
      { value: '2', label: '中专/中技' },
      { value: '3', label: '高中' },
      { value: '4', label: '大专' },
      { value: '5', label: '本科' },
      { value: '6', label: '硕士' },
      { value: '7', label: '博士' }
    ]
  },
  {
    id: 'workExperience',
    title: '工作经验',
    multiple: true, // 单选模式
    options: [
      { value: '', label: '不限' },
      { value: '1', label: '应届生' },
      { value: '2', label: '1-3年' },
      { value: '3', label: '3-5年' },
      { value: '4', label: '5年以上' }
    ]
  }
]);

// 获取学历标签
const getDegreeLabel = (degreeValue) => {
  const degreeGroup = filterGroups.value.find(g => g.id === 'degree');
  if (!degreeGroup) return degreeValue;
  
  const option = degreeGroup.options.find(o => o.value === degreeValue);
  return option ? option.label : degreeValue;
};

// 获取经验标签
const getExperienceLabel = (experienceValue) => {
  const expGroup = filterGroups.value.find(g => g.id === 'workExperience');
  if (!expGroup) return experienceValue;
  
  const option = expGroup.options.find(o => o.value === experienceValue);
  return option ? option.label : experienceValue;
};

// 格式化内容（将\n转换为<br>）
const formatContent = (content) => {
  if (Array.isArray(content)) {
    return content.join('<br>')
  }
  return content?.replace(/\n/g, '<br>') || ''
}

//收藏职位
const toggleFavorite = async (job) => {
  try {
    // 立即更新UI状态
    job.isCollect = !job.isCollect;
    
    if (job.isCollect) {
      // 调用收藏接口
      await insertPostCollect({ postId: job.id });
    } else {
      // 调用取消收藏接口
      await deletePostCollect({ postId: job.id });
    }
    
  } catch (error) {
    // 失败时回滚UI状态
    job.isCollect = !job.isCollect;
    console.error('收藏操作失败:', error);
  }
};
//分享职位
const qrcodeUrls = ref({})
const shareLinks = ref({})

const generateQRCode = async jobId => {
  const link = `${window.location.origin}${process.env.BASE_URL}recruitment/user/apply?jobId=${jobId}&groupId=${localStorage.getItem('recruitment-groupId')}`
  shareLinks.value[jobId] = link

  if (!qrcodeUrls.value[jobId]) {
    try {
      const url = await QRCode.toDataURL(link, {
        width: 120, // 减小二维码尺寸
        margin: 0,
        color: {
          dark: '#000',
          light: '#fff'
        }
      })
      qrcodeUrls.value[jobId] = url
    } catch (err) {
      console.error(err)
    }
  }
}

const copyLink = async jobId => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(shareLinks.value[jobId])
    } else {
      const textArea = document.createElement('textarea')
      textArea.value = shareLinks.value[jobId]
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      textArea.remove()
    }
    ElMessage.success('链接已复制')
  } catch (err) {
    console.error(err)
    ElMessage.error('复制失败')
  }
}

//获取相关职位
const relatedLoading = ref(false);
const relatedList = ref([])
const getRecommend = async(data) => {
  relatedLoading.value = true;
  const res = await selectRecommend({
    postName:data.name,
    num:10,
    groupId:store.state.base.userInfo.groupId
  })
  if (res.code === 20000) {
    relatedList.value = res.data;
  }
  relatedLoading.value = false;
}
const handleJobClick = jobId => {
  router.push(`/recruitment/user/apply?jobId=${jobId}`)
}

const isLoading = ref(false);
const debouncedFetch = myDebounce(async () => {
  if (isLoading.value) return;
  isLoading.value = true;
  
  try {
    await handleGetJobDetail();
  } finally {
    isLoading.value = false;
  }
}, 300);
// 监听 jobId 变化
watch(
  () => route.query.jobId,
  debouncedFetch,
  { immediate: true }
);
// 处理申请按钮点击

// const formUrl = ref('')
// const formLoading = ref(false)
const handleLogin = () => {
  if (process.env.NODE_ENV === 'development') {
    window.location.href = location.protocol + '//' + location.hostname + ':8100/login/index?redirect=' + location.href
  } else {
    window.location.href = location.protocol + '//' + location.hostname + `${location.port ? `:${location.port}` : ''}` + '/ram/login/index?redirect=' + location.href
  }
}
const handleApply = async () => {
  //判断用户是否登录
  if (!hasToken.value) {
    ElMessage({
      showClose: true,
      message: '请先登录',
      type: 'warning'
    })
    setTimeout(() => {
      handleLogin()
    }, 1000) // 延迟跳转登录页
    return
  }

  const res = await selectFormLink({ formId: jobDetail.value.paperId })
  if (!res.data.link) {
    ElMessage.error('申请表获取失败')
    return
  }
  let link
  if (process.env.NODE_ENV === 'development') {
    link = location.protocol + '//' + location.hostname + ':8080/?formKey=' + res.data.link
  } else {
    link = location.origin + '/formFront?formKey=' + res.data.link
  }
  const callbackQuery = encrypt({
    callbackUrl: '/recruitment/record/insert',
    sourceSystem: 'recruitment',
    timestamp: dayjs().unix(),
    data: {
      postId: route.query.jobId
    }
  })
  // 设置iframe的src
  // formUrl.value = `${link}&callback=${callbackQuery}`
  window.location.href = `${link}&callback=${callbackQuery}`
  // showIframe.value = true
  // formLoading.value = true
}

// const applyIframe = ref(null)

// // 处理iframe加载完成后的逻辑
// const handleIframeLoad = () => {
//   if (!applyIframe.value) return
//   formLoading.value = false
//   // 添加消息监听
//   window.addEventListener('message', (event) => {
//     const { type, height } = event.data
//     if (type === 'form-setHeight' && height) {
//       applyIframe.value.style.height = `${height}px`
//     }
//   })
// }

// // 添加窗口大小改变的监听
// const handleResize = () => {
//   if (showIframe.value) {
//     handleIframeLoad()
//   }
// }

onMounted(async () => {
  // if (route.query.groupId) {
  //   localStorage.setItem('recruitment-groupId', route.query.groupId)
  // }
  // await handleGetJobDetail()
  // getRecommend()
  // window.addEventListener('resize', handleResize)
})

// onUnmounted(() => {
//   window.removeEventListener('resize', handleResize)
// })
</script>

<style lang="scss" scoped>
  .inside-comment {
    padding: px2rem(40) 0 px2rem(80);
    .apply-container {
      .layout {
        display: flex;
        justify-content: space-between;
        .job-detail {
          width: 66%;
          .job-header {
            background-color: #f8f9fa;
            border-radius: px2rem(10);
            padding: px2rem(40);
            margin-bottom: px2rem(40);
            .top {
              display: flex;
              justify-content: space-between;
              align-items: center;
              .tit {
                font-size: px2rem(24);
                color: var(--el-color-primary);
                font-weight: bold;
              }
              .period {
                font-size: px2rem(16);
                color: #666;
                line-height: 1;
              }
            }
            .requirements {
                margin-top: px2rem(20);
                display: flex;
                align-items: center;
                gap: px2rem(5);
                font-size: px2rem(14);
                line-height: 1;
                color: #666;
                flex-wrap:wrap;
                .requirement-item {
                    display: flex;
                    align-items: center;
                    
                }
            }
            .job-tags {
                display: flex;
                flex-wrap:wrap;
                gap:px2rem(10);
                margin-top: px2rem(20);
            }
            .job-actions {
              margin-top: px2rem(20);
            }
          }
          .job-main {
            background-color: white;
            border-radius: px2rem(10);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            padding: px2rem(40);
            .job-section {
              margin-bottom: px2rem(40);
              h2 {
                font-size: px2rem(22);
                color: var(--el-color-primary);
                margin-bottom: px2rem(20);
                padding-bottom: px2rem(10);
                border-bottom: 1px solid #eee;
              }
            }
          }
          .related-jobs {
            margin-top: px2rem(40);
            .job-list {
              margin-top: px2rem(20);
              padding: 0;
              li {
                display: flex;
                flex-direction: column;
                border: 1px solid #eee;
                border-radius: 8px;
                padding: px2rem(20);
                box-sizing: border-box;
                margin-bottom: px2rem(20);
                transition: all 0.3s;
                &:hover {
                  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                  transform: translateY(-2px);
                }
                .top {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    .tit {
                        font-size: px2rem(18);
                        color: var(--el-color-primary);
                    }
                    .period {
                        font-size: px2rem(16);
                        flex-shrink: 0;
                        color: #666;
                        line-height: 1;
                    }
                }
                .requirements {
                    margin-top: px2rem(20);
                    display: flex;
                    align-items: center;
                    font-size: px2rem(14);
                    line-height: 1;
                    color: #666;
                    flex-wrap:wrap;
                    gap: px2rem(5);
                    .requirement-item {
                        display: flex;
                        align-items: center;
                        
                    }
                }
                .bottom {
                  margin-top: px2rem(20);
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  .job-tags {
                    display: flex;
                    flex-wrap:wrap;
                    gap:px2rem(10);
                  }
                }
              }
            }
          }
        }
        .job-sidebar {
          width: 30%;
          .sidebar-card {
            background-color: white;
            border-radius: px2rem(10);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            padding: px2rem(20);
            margin-bottom: px2rem(30);
            h3 {
              font-size: px2rem(18);
              margin-bottom: px2rem(20);
              color: var(--el-color-primary);
            }
            .sidebar-info {
              display: flex;
              align-items: center;
              gap: px2rem(10);
              margin-bottom: px2rem(10);
              i {
                color: var(--el-color-primary);
                font-size: px2rem(20);
              }
              a:hover {
                color: var(--el-color-primary);
              }
            }
          }
        }
      }
    }
  }
  .share-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 8px;
  box-sizing: border-box;
  .qrcode-img {
    width: 120px; // 减小二维码尺寸
    height: 120px;
    display: block;
  }

  .share-link {
    width: 100%;
  }

  .share-tip {
    color: #909399;
    font-size: 12px;
  }
}
@media (max-width: 960px) {
  .inside-comment {
    padding-top: 20px;
    .apply-container .layout {
      display: block;
      .job-detail {
        width: 100%;
        .job-header {
          padding: 20px;
          .top {
            flex-wrap: wrap;
            gap: 10px;
          }
        }
        .job-main {
          padding: 20px;
        }
      }
      .job-sidebar {
        width: 100%;
      }
    }
  }
}

.iframe-container {
  
}

.apply-iframe {
  width: 100%;
  min-height: calc(100vh - 100px);
  border: none;
  display: block;
  overflow: auto;
  transition: height 0.3s;
}

@media (max-width: 768px) {
  .apply-container {
    padding: 0 10px;
  }
}
</style>
